from typing import Optional, List, Dict, Any, Callable
from .executor import AbstractExecutor, ExecutionContext, Tuple, Schema
# 将第3行改为绝对导入
import struct

class SeqScanExecutor(AbstractExecutor):
    """顺序扫描执行器
    
    从表中顺序读取所有记录
    """
    
    def __init__(self, context: ExecutionContext, table_name: str,schema: Schema):
        super().__init__(context,schema)
        self.table_name = table_name
        self.schema = schema
        self.table = None
        self.uids = []  # 存储符合条件的UID列表
        self.current_uid_index = 0  # 当前处理的UID索引
        self.finished = False
        self.where_conditions = None # 存储where条件
    
    def init(self) -> None:
        """初始化扫描器"""
        self.table = self.context.get_table(self.table_name)
        if self.table is None:
            raise ValueError(f"Table '{self.table_name}' not found")

        # 直接获取符合条件的UID列表
        self.uids = self.table.select(0, self.where_conditions)

        self.current_uid_index = 0
        self.finished = False
    
    def next(self) -> Optional[Tuple]:
        """获取下一个元组"""
        if self.finished or self.table is None or self.current_uid_index >= len(self.uids):
            self.finished = True
            return None
        
        # 获取当前UID
        uid = self.uids[self.current_uid_index]
        self.current_uid_index += 1

        
        try:
            # 读取记录
            record_tuple = self.table.read(uid)
            if record_tuple is None:
                return self.next()
            record_tuple.schema=self.schema
            return record_tuple
        except TypeError as te:
            import traceback
            print(f"警告: 读取或解析 UID {uid} 的记录时发生类型错误，已跳过。错误: {te}")
            traceback.print_exc()  # 打印详细信息以供调试
            return self.next()  # 跳过这条损坏的记录，继续执行
        except Exception as e:
            import traceback
            traceback.print_exc()  # 打印详细堆栈以供调试
            raise RuntimeError(f"读取或解析 UID {uid} 的记录时发生严重错误: {e}")